/*
 * Copyright (c) 2011 Imre Fazekas.
 * All rights reserved.
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 * Neither the name of the Brillien nor the names of its
 * terms and concepts may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

package com.vii.brillien.core.management;


import com.vii.brillien.core.management.db.couchdbDocument.IndispensableFlow;
import com.vii.brillien.core.management.db.couchdbDocument.NodePresence;
import com.vii.brillien.ignition.transport.BrillienCommunication;

import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

import static com.vii.brillien.ignition.BrillienContext.*;

public class MessageControlCenter {

    private static ConcurrentHashMap<BrillienCommunication, ConcurrentLinkedQueue<BrillienCommunication>>   threads;
    private static ConcurrentHashMap<BrillienCommunication, BrillienCommunication>                          reverse;


    private static ConcurrentLinkedQueue<IndispensableFlow>                                     flows;
    private static NodePresence                                                                 presence;
    private static long                                                                         lastReport;



    static{
        threads = new ConcurrentHashMap<BrillienCommunication, ConcurrentLinkedQueue<BrillienCommunication>>();
        reverse = new ConcurrentHashMap<BrillienCommunication, BrillienCommunication>();

        flows   = new ConcurrentLinkedQueue<IndispensableFlow>();
    }

    private static void initNodePresence(){
        presence = new NodePresence();
        presence.setServerName( SERVER_NAME );
        presence.setServerVersion( SERVER_VERSION );
        presence.setJmxServicePort( JMX_SERVICE_PORT );
        presence.setJmxServiceOn( JMX_SERVICE_ON );
        presence.setLastReport( System.currentTimeMillis() );
    }



    public static void registerSubThread(BrillienCommunication sourceCommunication, BrillienCommunication initiatedCommunication){
        if( sourceCommunication == null )
            return;

        if( !threads.containsKey( sourceCommunication ) )
            threads.put( sourceCommunication, new ConcurrentLinkedQueue<BrillienCommunication>() );

        if( !threads.get( sourceCommunication ).contains( initiatedCommunication ) ){
            reverse.put( initiatedCommunication, sourceCommunication );
            threads.get( sourceCommunication ).add( initiatedCommunication );
        }

        System.out.println("-------------------------------------------------------------");
        System.out.println(threads);
        System.out.println(reverse);
        System.out.println("-------------------------------------------------------------");
    }


    public static BrillienCommunication examineSubThread(BrillienCommunication sourceCommunication){
        return  threads.containsKey(sourceCommunication) && threads.get( sourceCommunication ).isEmpty()
                ? sourceCommunication
                : null;
    }


    public static BrillienCommunication deregisterSubThread(BrillienCommunication message){
        BrillienCommunication sourceCommunication = null;
        BrillienCommunication initiatedCommunication = null;

        try{
            for(BrillienCommunication msg : reverse.keySet())
                if( message.isAnswerTo(msg) ){
                    sourceCommunication = reverse.get( msg );
                    initiatedCommunication = msg;
                    break;
                }

            if( sourceCommunication != null ){
                ConcurrentLinkedQueue<BrillienCommunication> queue = threads.get( sourceCommunication );

                reverse.remove( initiatedCommunication );
                queue.remove( initiatedCommunication );

                if( queue.isEmpty() )
                    return sourceCommunication;
            }
        } finally {
            System.out.println("-------------------------------------------------------------");
            System.out.println(threads);
            System.out.println(reverse);
            System.out.println("-------------------------------------------------------------");
        }
        return null;
    }


    public static void terminateSubThread(BrillienCommunication sourceCommunication){
        if( sourceCommunication != null )
            threads.remove( sourceCommunication );
    }


    public static synchronized boolean heartBeat(){
        if( presence == null )
            initNodePresence();

        presence.setLastReport( lastReport = System.currentTimeMillis() );

        return true;
    }

    public static IndispensableFlow getSuspendedFlowStateSpaceByID( String flowID ) {
        for (IndispensableFlow flow : flows) {
            if( flow.getStatus().equalsIgnoreCase("Suspended") && flow.getId().equals( flowID )  )
                return flow;
        }
        return null;
    }

    public static boolean refreshIndispensableFlow( IndispensableFlow ifd ) {
        return true;
    }

    public static List<IndispensableFlow> getLostFlows() {
        List<IndispensableFlow> flows = new LinkedList<IndispensableFlow>();
        for (IndispensableFlow flow : flows) {
            if( flow.getStatus().equalsIgnoreCase("Started") )
                flows.add( flow );
        }
        return flows;
    }

    public static IndispensableFlow getFlowByID( String flowID ) {
        for (IndispensableFlow flow : flows) {
            if( flow.getId().equals( flowID )  )
                return flow;
        }
        return null;
    }

    public static boolean reportChangedState( String flowID, HashMap<String, Object> state ){
        try{
            IndispensableFlow ifd = getFlowByID(flowID);
            ifd.setFlowStateSpace( state );
        }catch(Exception e){
            exceptionLog(CouchDBServices.class.getName(), "reportChangedState", e);
        }
        return true;
    }

    public static boolean reportFlowSuspense( String flowID, HashMap<String, Object> state ){
        try{
            IndispensableFlow ifd = getFlowByID(flowID);
            ifd.setFlowStateSpace( state );
            ifd.setStatus( IndispensableFlow.FLOW_SUSPENDED );
        }catch(Exception e){
            exceptionLog(CouchDBServices.class.getName(), "reportFlowSuspense", e);
        }
        return true;
    }

    public static boolean reportFlowReactivation( String flowID ){
        try{
            IndispensableFlow ifd = getFlowByID(flowID);
            ifd.setStatus( IndispensableFlow.FLOW_STARTED );
        }catch(Exception e){
            exceptionLog(CouchDBServices.class.getName(), "reportFlowReactivation", e);
        }
        return true;
    }

    public static boolean reportFlowFailure(String flowID, String message ) {
        try{
            IndispensableFlow ifd = getFlowByID(flowID);
            ifd.setStatus( IndispensableFlow.FLOW_FAILED );
            ifd.setFailureMessage( message );
        }catch(Exception e){
            exceptionLog(CouchDBServices.class.getName(), "reportFlowTermination", e);
        }
        return true;
    }

    public static boolean reportFlowTermination(String flowID) {
        try{
            IndispensableFlow ifd = getFlowByID(flowID);
            ifd.setStatus( IndispensableFlow.FLOW_FINISHED );
        }catch(Exception e){
            exceptionLog(CouchDBServices.class.getName(), "reportFlowTermination", e);
        }
        return true;
    }

    public static synchronized String getDelegationNode(){
        return SERVER_NAME;
    }

    public static boolean flowStarted(String flowID, String name, HashMap<String, Object> state, long timeout, BrillienCommunication bm ) throws IOException {
        IndispensableFlow ifd = new IndispensableFlow();
        ifd.setId( flowID );
        ifd.setFlowName( name );
        ifd.setFlowStateSpace( state );
        ifd.setStatus( IndispensableFlow.FLOW_STARTED );
        ifd.setStartDate( System.currentTimeMillis() );
        ifd.setTimeout( timeout );
        ifd.setActivationMessage( bm );
        ifd.setStartedBy( SERVER_NAME );

        ifd.setDelegatedTo(
                getDelegationNode()
        );

        flows.add( ifd );

        return true;
    }

}
